import React, { useState, useEffect, useRef } from 'react';
import { Card, Progress, Tag, Tooltip, Typography, Avatar, Badge, Popover, message } from 'antd';
import { 
  UserOutlined,
  AuditOutlined,
  NodeExpandOutlined,
  AppstoreOutlined,
  CaretUpOutlined, 
  MinusOutlined, 
  CaretDownOutlined,
  CalendarOutlined,
  PartitionOutlined,  // 父任务图标
  SubnodeOutlined,    // 子任务图标
  LinkOutlined
} from '@ant-design/icons';
import { Task, TaskLevel } from '../models/taskModels';
import TaskDetailModal from './TaskDetailModal';
import { Draggable } from 'react-beautiful-dnd';
import dayjs from 'dayjs';
import { getTaskByTitleIndex, getChildTasks } from '../../../services/taskService';

const { Title, Text } = Typography;

// 自定义图标组件
const HighOutlined: React.FC<{ className?: string }> = ({ className }) => {
  return <CaretUpOutlined className={className} />;
};

const MediumOutlined: React.FC<{ className?: string }> = ({ className }) => {
  return <MinusOutlined className={className} />;
};

const LowOutlined: React.FC<{ className?: string }> = ({ className }) => {
  return <CaretDownOutlined className={className} />;
};

// 定义卡片属性
interface TaskCardProps {
  task: Task;
  index: number;
  onEditTask?: (task: Task) => void; // 添加编辑任务的回调函数
  scrollToTask?: (taskId: string | number) => void; // 添加滚动到任务的回调函数
}

// 简化的DraggableProvided接口
interface SimpleDraggableProvided {
  innerRef: React.Ref<any>;
  draggableProps: any;
  dragHandleProps: any | null;
}

/**
 * 任务卡片组件
 * 显示任务的基本信息，支持拖拽和展示详情
 */
const TaskCard: React.FC<TaskCardProps> = ({ task, index, onEditTask, scrollToTask }) => {
  // 控制任务详情弹窗的显示
  const [detailVisible, setDetailVisible] = useState(false);
  // 父任务信息
  const [parentTask, setParentTask] = useState<Task | null>(null);
  // 子任务列表
  const [childTasks, setChildTasks] = useState<Task[]>([]);
  // 加载状态
  const [loading, setLoading] = useState(false);
  // 当前闪烁的任务ID
  const [flashingTaskId, setFlashingTaskId] = useState<string | number | null>(null);
  // 使用message钩子代替静态方法
  const [messageApi, contextHolder] = message.useMessage();

  // 添加一个DOM引用
  const cardRef = useRef<HTMLDivElement | null>(null);

  // 加载关联任务信息
  useEffect(() => {
    const fetchRelatedTasks = async () => {
      try {
        setLoading(true);
        
        // 如果有父任务ID，获取父任务信息
        if (task.parentId) {
          const parentResponse = await getTaskByTitleIndex(task.parentId);
          if (parentResponse.code === 200 && parentResponse.data) {
            setParentTask(parentResponse.data);
          }
        }
        
        // 获取子任务列表
        if (task.titleIndex) {
          const childResponse = await getChildTasks(task.titleIndex);
          if (childResponse.code === 200 && childResponse.data) {
            setChildTasks(childResponse.data);
          }
        }
      } catch (error) {
        console.error('加载关联任务失败:', error);
      } finally {
        setLoading(false);
      }
    };
    
    fetchRelatedTasks();
  }, [task.parentId, task.titleIndex]);

  // 执行闪烁效果
  const handleFlash = (taskId: string | number) => {
    console.log('【父子任务】开始处理闪烁效果, 目标任务ID:', taskId, '当前任务ID:', task.id);
    
    // 先调用scrollToTask函数，它会将任务移到列顶部并滚动到该位置
    if (scrollToTask) {
      console.log('【父子任务】调用scrollToTask函数, 将任务移到列顶部并滚动, 目标任务ID:', taskId);
      scrollToTask(taskId);
    } else {
      console.warn('【父子任务】scrollToTask回调未提供，无法移动任务到列顶部');
    }
    
    if (String(taskId) === String(task.id)) {
      console.log('【父子任务】目标任务匹配当前任务，应用视觉特效');
      setFlashingTaskId(taskId);
      
      // 应用额外的动画效果
      if (cardRef.current) {
        console.log('【父子任务】找到卡片DOM元素，应用动画和样式特效');
        
        // 保存原始背景色
        const originalBg = cardRef.current.style.backgroundColor;
        const originalTransform = cardRef.current.style.transform;
        const originalZIndex = cardRef.current.style.zIndex;
        const originalBorder = cardRef.current.style.border;
        
        // 设置高亮样式
        cardRef.current.style.backgroundColor = '#ffffcc';  // 黄色背景
        cardRef.current.style.transform = 'scale(1.05)';    // 放大效果
        cardRef.current.style.zIndex = '999';              // 置于最上层
        cardRef.current.style.border = '2px solid #ff4d4f'; // 红色边框
        cardRef.current.style.transition = 'all 0.3s ease-in-out';
        
        console.log('【父子任务】视觉特效已应用：黄色背景、放大比例、红色边框');
        
        // 添加震动效果
        const shakeCard = () => {
          const element = cardRef.current;
          if (!element) return;
          
          console.log('【父子任务】开始执行震动特效，震动次数:', 5);
          
          let count = 0;
          const maxCount = 5;
          const interval = setInterval(() => {
            if (count >= maxCount || !element) {
              clearInterval(interval);
              console.log('【父子任务】震动特效完成，已执行震动次数:', count);
              return;
            }
            
            const direction = count % 2 === 0 ? 5 : -5;
            element.style.transform = `scale(1.05) translateX(${direction}px)`;
            console.log('【父子任务】执行第', count+1, '次震动，方向:', direction);
            count++;
          }, 100);
          
          // 最后恢复原位
          setTimeout(() => {
            if (element) {
              element.style.transform = 'scale(1.05)';
              console.log('【父子任务】震动完成后恢复放大效果，不再震动');
            }
          }, (maxCount + 1) * 100);
        };
        
        // 启动震动效果
        shakeCard();
        
        // 5秒后恢复原状
        setTimeout(() => {
          if (cardRef.current) {
            console.log('【父子任务】特效持续5秒结束，开始恢复原始样式');
            cardRef.current.style.backgroundColor = originalBg;
            cardRef.current.style.transform = originalTransform;
            cardRef.current.style.zIndex = originalZIndex;
            cardRef.current.style.border = originalBorder;
            console.log('【父子任务】特效已完全清除，卡片恢复正常外观');
          }
          setFlashingTaskId(null);
          console.log('【父子任务】闪烁状态已重置，特效流程完成');
        }, 5000);
      } else {
        console.warn('【父子任务】未找到卡片DOM元素，无法应用视觉特效');
      }
    } else {
      console.log('【父子任务】当前任务不是目标任务，不应用闪烁效果');
    }
  };

  // 根据任务优先级获取对应图标
  const getLevelIcon = (level: TaskLevel) => {
    switch(level) {
      case '高':
        return <HighOutlined className="text-red-500" />;
      case '中':
        return <MediumOutlined className="text-orange-500" />;
      case '低':
        return <LowOutlined className="text-green-500" />;
      default:
        return null;
    }
  };

  // 根据状态获取颜色
  const getStatusColor = (status: string) => {
    switch(status) {
      case 'todo':
        return 'blue';
      case 'inProgress':
        return 'orange';
      case 'done':
        return 'green';
      default:
        return 'default';
    }
  };

  // 获取进度条状态
  const getProgressStatus = (process?: number) => {
    if (process === undefined) return 'normal';
    if (process >= 100) return 'success';
    if (process > 0) return 'active';
    return 'normal';
  };

  // 获取类型标签颜色
  const getTypeColor = (type: string) => {
    return type === '业务需求' ? 'cyan' : 'purple';
  };

  // 获取子类型标签颜色
  const getSubTypeColor = (subType: string) => {
    switch(subType) {
      case '业务自驱型':
        return 'blue';
      case '平台赋能型':
        return 'cyan';
      case '联合攻坚型':
        return 'geekblue';
      case '个人效能提升':
        return 'magenta';
      case '公共工具建设':
        return 'purple';
      case '数字员工建设':
        return 'volcano';
      default:
        return 'default';
    }
  };

  // 状态和进度的显示文字
  const statusText = {
    'todo': '待处理',
    'inProgress': '进行中',
    'done': '已完成'
  };

  // 获取处理人显示名称，只显示中文名
  const getReceiverDisplayNames = (receiverStr?: string): string => {
    if (!receiverStr) return '';
    
    // 将多个处理人分割并只显示中文名
    return receiverStr.split('|').map(item => {
      const parts = item.split('/');
      if (parts.length >= 2) {
        return parts[1]; // 返回中文名部分
      }
      return item; // 如果格式不符合，返回原始值
    }).join(', ');
  };

  // 处理编辑按钮点击
  const handleEdit = () => {
    setDetailVisible(false); // 关闭详情弹窗
    // 如果父组件提供了编辑回调，则调用
    if (onEditTask) {
      onEditTask(task);
    }
  };

  // 点击父任务图标
  const handleParentClick = () => {
    if (parentTask) {
      console.log('【父子任务】点击父任务图标, 父任务:', parentTask.title, 'ID:', parentTask.id);
      messageApi.info(`跳转至父任务: ${parentTask.title}`);
      handleFlash(parentTask.id);
    } else {
      console.warn('【父子任务】点击父任务图标，但父任务信息不存在');
    }
  };
  
  // 点击子任务图标
  const handleChildClick = (childTask: Task) => {
    console.log('【父子任务】点击子任务图标, 子任务:', childTask.title, 'ID:', childTask.id);
    messageApi.info(`跳转至子任务: ${childTask.title}`);
    handleFlash(childTask.id);
  };
  
  // 渲染父任务图标
  const renderParentTaskIcon = () => {
    if (!task.parentId || !parentTask) return null;
    
    return (
      <Tooltip title={`父任务：${parentTask.title}`}>
        <div 
          className="flex items-center bg-blue-100 rounded-md px-2 py-1 cursor-pointer hover:bg-blue-200 transition-colors"
          onClick={(e) => {
            e.stopPropagation();
            handleParentClick();
          }}
        >
          <PartitionOutlined style={{ color: '#1890ff', fontSize: '16px' }} className="mr-1" />
          <span className="text-blue-700 text-sm font-medium">父任务</span>
        </div>
      </Tooltip>
    );
  };
  
  // 渲染子任务图标
  const renderChildTaskIcons = () => {
    if (!childTasks.length) return null;
    
    return (
      <div className="flex flex-wrap gap-1">
        {childTasks.map((childTask, idx) => (
          <Tooltip key={childTask.id} title={`子任务${idx + 1}：${childTask.title}`}>
            <div 
              className="flex items-center bg-green-100 rounded-md px-2 py-1 cursor-pointer hover:bg-green-200 transition-colors"
              onClick={(e) => {
                e.stopPropagation();
                handleChildClick(childTask);
              }}
            >
              <SubnodeOutlined style={{ color: '#52c41a', fontSize: '16px' }} className="mr-1" />
              <span className="text-green-700 text-sm font-medium">子任务{idx + 1}</span>
            </div>
          </Tooltip>
        ))}
      </div>
    );
  };

  // 计算卡片样式，添加闪烁效果
  const getCardStyle = () => {
    const baseStyle = {
      borderLeftColor: task.status === 'todo' ? '#1890ff' : task.status === 'inProgress' ? '#fa8c16' : '#52c41a',
    };
    
    // 如果是当前闪烁的任务，添加闪烁动画样式
    if (flashingTaskId === task.id) {
      console.log('【父子任务】应用闪烁样式到卡片, 任务ID:', task.id);
      return {
        ...baseStyle,
        animation: 'card-highlight 1s ease-in-out 5',
        boxShadow: '0 0 20px rgba(255, 0, 0, 0.8)',
        border: '2px solid #ff4d4f',
      };
    }
    
    return baseStyle;
  };
  
  // 添加全局动画样式
  useEffect(() => {
    console.log('【父子任务】添加全局动画样式');
    const styleElement = document.createElement('style');
    styleElement.innerHTML = `
      @keyframes card-highlight {
        0%, 100% { 
          box-shadow: 0 0 15px rgba(255, 0, 0, 0.3);
          border-color: rgba(255, 0, 0, 0.3);
        }
        50% { 
          box-shadow: 0 0 30px rgba(255, 0, 0, 1);
          border-color: rgba(255, 0, 0, 1);
        }
      }
      
      @keyframes card-pulse {
        0%, 100% { transform: scale(1); }
        50% { transform: scale(1.05); }
      }
      
      .task-card-highlight {
        animation: card-pulse 0.5s ease-in-out infinite !important;
        box-shadow: 0 0 20px rgba(255, 0, 0, 0.8) !important;
        border: 2px solid #ff4d4f !important;
        background-color: rgba(255, 255, 150, 0.3) !important;
      }
    `;
    document.head.appendChild(styleElement);
    
    return () => {
      console.log('【父子任务】移除全局动画样式');
      document.head.removeChild(styleElement);
    };
  }, []);

  // 监听闪烁状态变化，添加或移除高亮类
  useEffect(() => {
    if (cardRef.current) {
      if (flashingTaskId === task.id) {
        console.log('【父子任务】添加高亮样式类 task-card-highlight');
        cardRef.current.classList.add('task-card-highlight');
      } else {
        cardRef.current.classList.remove('task-card-highlight');
      }
    }
  }, [flashingTaskId, task.id]);

  return (
    <Draggable draggableId={String(task.id)} index={index}>
      {(provided: SimpleDraggableProvided) => {
        return (
          <div
            ref={(el) => {
              // 在ref回调中分别设置两个引用
              if (provided.innerRef && typeof provided.innerRef === 'function') {
                provided.innerRef(el);
              }
              cardRef.current = el;
            }}
            {...provided.draggableProps}
            {...provided.dragHandleProps}
            className="mb-4"
            id={`task-${task.id}`}
            data-task-id={task.id}
          >
            {/* 消息上下文提供者 */}
            {contextHolder}
            
            <Card
              className="hover:shadow-md transition-shadow duration-300 cursor-pointer transform hover:-translate-y-1 border-l-4"
              style={getCardStyle()}
              onClick={() => setDetailVisible(true)}
              size="small"
            >
              <div className="flex flex-col">
                {/* 任务标题和进度 */}
                <div className="mb-2">
                  <div className="flex justify-between items-start mb-2">
                    <Title level={5} className="m-0 text-gray-800">
                      {task.title}
                    </Title>
                  </div>
                  
                  {/* 父子任务标签 */}
                  <div className="flex flex-wrap gap-1 mb-2">
                    {renderParentTaskIcon()}
                    {renderChildTaskIcons()}
                  </div>
                  
                  <div className="mt-2">
                    <Progress 
                      percent={task.process ?? 0} 
                      size="small" 
                      status={getProgressStatus(task.process) as "success" | "normal" | "active" | "exception"}
                      strokeColor={{
                        '0%': '#108ee9',
                        '100%': '#87d068',
                      }}
                    />
                  </div>
                </div>

                {/* 任务类型信息 */}
                <div className="flex flex-wrap gap-1 mb-2">
                  <Tag icon={<AppstoreOutlined />} color={getTypeColor(task.type)}>
                    {task.type}
                  </Tag>
                  <Tag icon={<NodeExpandOutlined />} color={getSubTypeColor(task.subType)}>
                    {task.subType}
                  </Tag>
                  <Tag icon={getLevelIcon(task.level)} color={task.level === '高' ? 'red' : task.level === '中' ? 'orange' : 'green'}>
                    {task.level}复杂度
                  </Tag>
                </div>

                {/* 人员信息 */}
                <div className="flex justify-between text-gray-600 text-sm mt-2">
                  <Tooltip title={`创建人: ${task.creater}`}>
                    <div className="flex items-center bg-blue-50 rounded-md px-2 py-1">
                      <Avatar size="small" icon={<UserOutlined />} className="mr-1" />
                      <Text ellipsis={{ tooltip: task.creater }} className="max-w-[60px]">
                        {task.creater}
                      </Text>
                    </div>
                  </Tooltip>
                  
                  {task.receiver && (
                    <Tooltip title={`处理人: ${getReceiverDisplayNames(task.receiver)}`}>
                      <div className="flex items-center bg-green-50 rounded-md px-2 py-1">
                        <Avatar size="small" icon={<AuditOutlined />} className="mr-1" />
                        <Text ellipsis={{ tooltip: getReceiverDisplayNames(task.receiver) }} className="max-w-[80px]">
                          {getReceiverDisplayNames(task.receiver)}
                        </Text>
                      </div>
                    </Tooltip>
                  )}
                </div>

                {/* 日期信息 */}
                <div className="flex justify-between text-gray-500 text-xs mt-2">
                  {task.expectedDate && (
                    <Tooltip title={`期望完成: ${dayjs(task.expectedDate).format('YYYY-MM-DD')}`}>
                      <div className="flex items-center">
                        <CalendarOutlined className="mr-1" />
                        <span>期望: {dayjs(task.expectedDate).format('MM-DD')}</span>
                      </div>
                    </Tooltip>
                  )}
                  {task.finishedDate && task.status === 'done' && (
                    <Tooltip title={`实际完成: ${dayjs(task.finishedDate).format('YYYY-MM-DD')}`}>
                      <div className="flex items-center text-green-600">
                        <CalendarOutlined className="mr-1" />
                        <span>完成: {dayjs(task.finishedDate).format('MM-DD')}</span>
                      </div>
                    </Tooltip>
                  )}
                </div>
              </div>
            </Card>

            {/* 任务详情弹窗 */}
            <TaskDetailModal
              visible={detailVisible}
              task={task}
              onCancel={() => setDetailVisible(false)}
              showEditButton={task.status === 'inProgress'}
              onEdit={handleEdit}
            />
          </div>
        );
      }}
    </Draggable>
  );
};

export default TaskCard; 